package br.com.framework.apresentacao.converter;

import java.util.Collection;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.framework.persistencia.model.BaseEntity;

public class EntityConverter<T extends BaseEntity> implements Converter {
	
	private Collection<T> entityList;

	/**
	 * @param entityList
	 */
	public EntityConverter(Collection<T> entityList) {
		this.entityList = entityList;
	}

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		// catch exceptions and empty or null value!
		for (T entity : this.entityList)
			if (entity.getId().toString().equals(value))
				return entity;
		return null;
	}

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		// catch null and instanceof
		return ((T) value).getId().toString();
	}

	public Collection<T> getEntityList() {
		return this.entityList;
	}
}